<?php
/*
Plugin Name: Stumble Info Link
Version: 0.5
Plugin URI: http://leau.net/su/
Author: Edward de Leau
Author URI: http://edward.de.leau.net
Description: Places a grey or colored stumble-upon icon and link behind each url

=>> Visit the plugin's homepage for more information and latest updates  <<=

Installation:

1. Upload the file in your plugins directory
2. Activate the plugin from your WordPress admin 'Plugins' page.

*/
/*
Copyright (c) 2006-2008 by Edward de Leau (aka Cogmios aka Edelwater)

v.0.1 primary version
v.0.2 skipped .zip, .pdf
v.0.3 added colors to the icon: grey if not in su, colored if it is
v.0.4 changed to use local rss reader and cache instead of my server!
v.0.5 bugfixed

*/

include_once(ABSPATH . WPINC . '/rss.php');

//
// Checks the StumbleUpon Url and return a number from 1-10
//
function checkSURating($feedUrl) {

	$shortHttpString = str_replace('http://', '', $feedUrl);
	$shortHttpString = str_replace('https://', '', $feedUrl);

	$feedUrl = 'http://www.stumbleupon.com/reviews.php?url=' . $feedUrl;
	$feed = fetch_rss("$feedUrl");
	if ($feed) {
		return count($feed->items);
	} else {
		return "-1";
	}

}

function strxchr($haystack, $needle, $l_inclusive = 0, $r_inclusive = 0){
   if (strrpos($haystack, $needle) !== false) {
       $left =  substr($haystack, 0, strrpos($haystack, $needle) + $l_inclusive);
       $r_inclusive = ($r_inclusive == 0) ? 1 : 0;
       $right =  substr(strrchr($haystack, $needle), $r_inclusive);
       $a = array($left, $right);
       return $a;
   } else{
       return false;
   }
}

function Replacer($matches) {
    $or_string  = '<a' . $matches[1] . 'href="' . $matches[2] . '"'.$matches[3].'>' . $matches[4] . '</a>';

    $st_string  = ' <a class="wpsulink" href="http://www.stumbleupon.com/url/' . $matches[2] . '" target="_blank">' .


	 $st_string = $st_string . ' (' . checkSURating($matches[2]) . ')';
    $st_string = $st_string . '</a>';

    // if the string contains any html tags we'll skip it, doesnt look good
    if (strstr ( $matches[4], '<' )) {
      return $or_string;
    } else {
      // if the url is a zip, pdf, etc... also skip it
      $foundstr = strxchr($matches[2], ".", 1, 1);
      if ($foundstr && (stristr('.zip .pdf .arj', $foundstr[1]) != FALSE)) {
            return $or_string;
      }
      return $or_string . $st_string;
    }
}

function add_stumble_icon ($text) {
    return preg_replace_callback('/<a(.*?)href="(.*?)"(.*?)>(.*?)<\\/a>/i', 'Replacer', $text);
}

add_filter('the_content', 'add_stumble_icon', 9);
?>
